/**
 * Summary: 应用中使用的WebChromeClient基类
 * Version 1.0
 * Date: 13-11-8
 * Time: 下午2:31
 * Copyright: Copyright (c) 2013
 */

package cn.pedant.SafeWebViewBridge;

import ohos.agp.components.webengine.BrowserAgent;
import ohos.agp.components.webengine.JsMessageResult;
import ohos.agp.components.webengine.JsTextInputResult;
import ohos.agp.components.webengine.WebView;
import ohos.app.Context;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

public class InjectedChromeClient extends BrowserAgent {
    private static final HiLogLabel TAG = new HiLogLabel(HiLog.LOG_APP,0x00020,"InjectedChromeClient");
    private static final int NUM_25 = 25;
    private JsCallJava mJsCallJava;
    private boolean isInjectedJs;

    /**
     * 构造
     *
     * @param context 上下文
     * @param injectedName 类名
     * @param injectedCls 类
     */
    public InjectedChromeClient(Context context,String injectedName, Class injectedCls) {
        super(context);
        mJsCallJava = new JsCallJava(injectedName, injectedCls);
    }

    /**
     * 构造
     *
     * @param context 上下文
     * @param jsCallJava 回调
     */
    public InjectedChromeClient(Context context, JsCallJava jsCallJava) {
        super(context);
        mJsCallJava = jsCallJava;
    }

    /**
     * 处理Alert事件
     *
     * @param webView webView
     * @param url url
     * @param message message
     * @param isAlert isAlert
     * @param result 结果
     * @return boolean
     */
    @Override
    public boolean onJsMessageShow(
            WebView webView, String url, String message, boolean isAlert, JsMessageResult result) {
        result.confirm();
        return true;
    }

    @Override
    public boolean onJsTextInput(
            WebView webView, String url, String message, String defaultInput, JsTextInputResult result) {
        result.respond(mJsCallJava.call(webView, message));
        result.respond(message);
        return true;
    }

    @Override
    public void onProgressUpdated(WebView webView, int newValue) {
        if (newValue <= NUM_25) {
            isInjectedJs = false;
        } else if (!isInjectedJs) {
            webView.load(mJsCallJava.getpreloadinterfaceJs());
            isInjectedJs = true;
            HiLog.info(TAG, " inject js interface completely on progress " + newValue);
        }
        super.onProgressUpdated(webView, newValue);
    }
}
